package com.example.myproject.distance;

import java.awt.geom.Point2D;

public class BaiduUtil2 {
    public static void main(String[] args) {
        try {
            // 太原
            Point2D pointDD = new Point2D.Double(112.53, 37.87);
            // 上海
            Point2D pointXD = new Point2D.Double(121.48, 31.22);
            System.out.println("太原－上海："+getDistance(pointDD, pointXD));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final double EARTH_RADIUS = 6371393; // 地球平均半径,单位：m

    /**
     * 通过AB点经纬度获取距离
     * 1102999.520054716
     * 1104167.0243607962,距离
     * 1103242.00000000
     * @param pointA A点(经，纬)
     * @param pointB B点(经，纬)
     * @return 距离(单位：米)
     */
    public static double getDistance(Point2D pointA, Point2D pointB) {
        // 经纬度（角度）转弧度。弧度用作参数，以调用Math.cos和Math.sin
        double radiansAX = Math.toRadians(pointA.getX()); // A经弧度
        double radiansAY = Math.toRadians(pointA.getY()); // A纬弧度
        double radiansBX = Math.toRadians(pointB.getX()); // B经弧度
        double radiansBY = Math.toRadians(pointB.getY()); // B纬弧度

        // cosβ1cosβ2cos（α1-α2）+sinβ1sinβ2
        double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX)
                + Math.sin(radiansAY) * Math.sin(radiansBY);
        double acos = Math.acos(cos); // 反余弦值
        return EARTH_RADIUS * acos; // 最终结果
    }


}
